package com.liuqianfei.markme.rules.inline;

import com.liuqianfei.markme.core.Token;
import com.liuqianfei.markme.rules.AbstractState;
import com.liuqianfei.markme.rules.IAction;
import com.liuqianfei.util.StringUtil;

/**
 * @author liuqianfei
 */
public class BacktickAction implements IAction
{
    @Override
    public boolean parse(AbstractState state, boolean silent, int startLine, int endLine)
    {
        Token token;

        String marker;
        int start, max, matchStart, matchEnd, pos = state.getPos();
        char ch = state.getSrc().charAt(pos);

        if (ch != 0x60/* ` */)
            return false;

        start = pos;
        pos++;
        max = state.getPosMax();

        while (pos < max && state.getSrc().charAt(pos) == 0x60/* ` */)
            pos++;

        marker = StringUtil.slice(state.getSrc(), start, pos);

        matchStart = matchEnd = pos;

        while ((matchStart = state.getSrc().indexOf('`', matchEnd)) != -1)
        {
            matchEnd = matchStart + 1;

            while (matchEnd < max && state.getSrc().charAt(matchEnd) == 0x60/* ` */)
                matchEnd++;

            if (matchEnd - matchStart == marker.length())
            {
                if (!silent)
                {
                    token         = state.push("code_inline", "code", 0);
                    token.markup  = marker;
                    token.content = StringUtil.slice(state.getSrc(), pos, matchStart).replaceAll("[ \n]+", " ").trim();
                }
                state.setPos(matchEnd);
                return true;
            }
        }

        if (!silent)
            state.setPending(state.getPending() + marker);

        state.setPos(state.getPos() + marker.length());
        return true;
    }
}
